/* 
 登录
 
 // 微信公众号H5登录
 // 这个写法在本地开发调试，因为本地运行路径不是微信公众平台配置的安全域名
 // 会报错误：redirect_uri 参数错误，建议使用服务端进行获取code登录
import { useLogin } from '@/hooks/useLogin.js'

// App第三方登录
const { oauthLogin } = useLogin()
try {
    const { code, userInfo } = await oauthLogin('weixin')
    // 处理登录结果
} catch (error) {
    // 处理错误
}

// 微信H5登录
const { weixinH5Login } = useLogin()
weixinH5Login().then(code => {
    // 获取到code
}).catch(err => {
    // 处理错误
})
 
 调用服务端接口写法
 onLoad(options => {
 	if (options.openid == null) {
 		var url = window.location.href
 		url = encodeURIComponent(url)
 		//请求后台进行跳转
 		location.href = "服务端接口api?returnUrl=" + url
		// 服务端登录成功回调openID
		// url?openid=xxx
 	} else {
		this.sjuLogin.saveValue("openID", options.openid)
	}
 })
 */
import * as appConfig from '@/config/config'

const useLogin = () => {
    // 浏览器判断是否微信
    const isWechat = () => {
        const ua = navigator.userAgent.toLowerCase()
        return ua.includes('micromessenger')
    }

    // 获取链接参数
    const getUrlParam = (name) => {
        const params = new URLSearchParams(window.location.search)
        return params.get(name)
    }

    /**
     * App第三方授权登录
     * @param {string} type 授权平台 weixin|qq|sinaweibo|xiaomi|univerify|apple|google|facebook
     * @returns {Promise} 返回登录结果
     */
    const oauthLogin = async (type) => {
        try {
            const loginRes = await uni.login({ provider: type })
            const userInfo = await uni.getUserInfo({ provider: type })
            return {
                code: loginRes.code,
                userInfo: userInfo.userInfo
            }
        } catch (error) {
            console.error('登录失败:', error)
            throw error
        }
    }

    /**
     * 小程序授权登录
     * @returns {Promise} 返回登录结果
     */
    const miniLogin = async () => {
        try {
            const { provider } = await uni.getProvider({ service: 'oauth' })
            const res = await uni.login({ provider })
            return res
        } catch (error) {
            console.error('小程序登录失败:', error)
            throw error
        }
    }

    /**
     * 微信H5登录
     * @returns {Promise} 返回code或跳转授权
     */
    const weixinH5Login = async () => {
        if (!isWechat()) {
            throw new Error('请在微信浏览器中打开')
        }

        const code = getUrlParam('code')
        if (code) return code

        const redirectUri = encodeURIComponent(window.location.href)
        const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appConfig.appInfo.appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
        
        window.location.href = authUrl
        return new Promise(() => {}) // 保持Promise链但不会resolve
    }

    return { 
        oauthLogin, 
        miniLogin, 
        weixinH5Login,
        isWechat
    }
}

export { useLogin }